package com.company.OfferGuide;

import com.company.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;

public class 重建二叉树 {

    public static void main(String[] args) {
        new 重建二叉树().buildTree(new int[]{3,9,20,15,7},new int[]{9,3,15,20,7});
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTree(preorder,inorder,0);
    }

    public TreeNode buildTree(int[] preorder, int[] inorder,int start) {
        if (preorder.length == 0 || inorder.length == 0) return null;
        int val = preorder[0];
        TreeNode treeNode = new TreeNode(val);
        int i = 0;
        while (inorder[i] != val) {
            i++;
        }
        treeNode.left = buildTree(Arrays.copyOfRange(preorder,1,preorder.length), Arrays.copyOfRange(inorder,0,i));
        treeNode.right = buildTree(Arrays.copyOfRange(preorder,i + 1,preorder.length), Arrays.copyOfRange(inorder,i + 1,inorder.length));

        return treeNode;
    }


}
